<template>
  <div v-show="offsetTop > distance" class="backTop" @click="backTop">
    <van-icon name="arrow-up" />
  </div>
</template>

<script>
export default {
  name: 'backTop',
  props: {
    distance: {
      type: Number,
      default: 600
    }
  },
  data () {
    return {
      // 滚动距离
      offsetTop: 0
    }
  },
  mounted () {
    // 检测屏幕滚动距离
    window.onscroll = () => {
      this.offsetTop = document.documentElement.scrollTop
    }
  },
  methods: {
    backTop () {
      // 取消滚动事件
      window.onscroll = null
      console.log(this.offsetTop)
      // 事件动画效果
      const timer = setInterval(() => {
        this.offsetTop -= 100
        console.log(this.offsetTop)
        window.scrollTo(0, this.offsetTop)
        // 到达顶部后重新监听事件,清除定时器
        if (this.offsetTop <= 0) {
          // 小于0设置为0
          this.offsetTop = 0
          console.log(this.offsetTop)
          window.onscroll = () => {
            this.offsetTop = document.documentElement.scrollTop
          }
          clearInterval(timer)
        }
      }, 5)
    }
  }
}
</script>

<style lang="less" scoped>
.backTop {
  background-color: orange;
  border: 1px solid #000;
  position: fixed;
  line-height: 40px;
  text-align: center;
  bottom: 80px;
  right: 30px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
</style>
